package com.heima.gateway.filter;

import com.heima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

/*
全局过滤器，校验token是否有效
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange 交换机，可以获取请求和响应对象
     * @param chain 过滤器链
     * @return
     */


    private static final String LOGIN_URL = "/user/api/v1/login/login_auth/";
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
       //TODO
        ServerHttpRequest request = exchange.getRequest();
        String requestPath = request.getPath().toString();



        // 判断是否是登录URL，如果是则直接放行
        if (requestPath.equals(LOGIN_URL)) {
            return chain.filter(exchange);
        }
        List<String> list = exchange.getRequest().getHeaders().get("token");
        String s = list.get(0);
        Claims claimsBody = AppJwtUtil.getClaimsBody(s);




        int i = AppJwtUtil.verifyToken(claimsBody);
        if (i<=0){
            return chain.filter(exchange);
        }
        return chain.filter(null);
    }

    /**
     * 过滤的执行的优先级，返回值越小优先级越高
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
